package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service

public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    /**
     * 分页条件查询
     *
     * @param student
     * @return
     */
    @Override
    public PageResult<Student> findPage(StudentQueryParam student) {
        Integer page = student.getPage();
        Integer pageSize = student.getPageSize();
        String name = student.getName();
        Integer degree = student.getDegree();
        Integer clazzId = student.getClazzId();
        IPage<Student> iPage=new Page<>(page,pageSize);
        iPage = this.page(iPage, Wrappers.<Student>lambdaQuery()
                .like(name != null, Student::getName, name)
                .eq(degree != null, Student::getDegree, degree)
                .eq(clazzId != null, Student::getClazzId, clazzId));
        List<Student> records = iPage.getRecords();
        if (!CollectionUtils.isEmpty(records)){
            for (Student record : records) {
                record.setClazzName(clazzMapper.selectById(record.getClazzId()).getName());
            }
        }
        return new PageResult<>(iPage.getTotal(),records);
    }

    /**
     * 新增学生
     *
     * @param student
     */
    @Override
    public void saveStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(LocalDateTime.now());
        this.save(student);
    }

    /**
     * 修改学生
     *
     * @param student
     */
    @Override
    public void updateStuById(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        this.updateById(student);
    }

    /**
     * 违纪处理
     *
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        if (id!=null){
            LambdaQueryWrapper<Student> eq = Wrappers.<Student>lambdaQuery().eq(id != null, Student::getId, id);
            studentMapper.violation(eq, score);
        }
    }
}
